#!/bin/bash

# 后台任务脚本 - 功能与background_task.bat相同
# 等待到下一个整点开始循环，全天24小时执行脚本
# 仅在工作时间(9-17点)随机打开网站，全天24小时执行repo_commit.sh

# 设置信号处理，允许优雅退出
trap 'echo "收到退出信号，正在优雅退出..."; exit 0' SIGTERM SIGINT

# 设置标志文件路径
GCM_TRIGGER_FILE="/tmp/gcm_trigger"

# 清理函数
cleanup() {
    rm -f "$GCM_TRIGGER_FILE"
    echo "后台任务清理完成"
}

# 注册清理函数
trap cleanup EXIT

# 检查是否有gcm触发信号
check_gcm_trigger() {
    if [ -f "$GCM_TRIGGER_FILE" ]; then
        echo "$(date): 检测到gcm触发信号，立即执行repo_commit.sh..."
        rm -f "$GCM_TRIGGER_FILE"
        execute_repo_commit
        echo "$(date): gcm触发执行完成"
        return 0
    fi
    return 1
}

# 等待到下一个整点（带中断检查）
wait_until_full_hour() {
    echo "等待到下一个整点..."
    
    # 获取当前时间
    current_hour=$(date +%H)
    current_minute=$(date +%M)
    current_second=$(date +%S)
    
    # 计算等待时间（秒）
    wait_minutes=$((59 - current_minute))
    wait_seconds=$((60 - current_second))
    total_wait_seconds=$((wait_minutes * 60 + wait_seconds))
    
    # 等待到下一个整点（分段睡眠，定期检查中断）
    if [ $total_wait_seconds -gt 0 ]; then
        echo "等待 $total_wait_seconds 秒直到下一个整点..."
        # 每10秒检查一次中断信号
        for ((i=0; i<$((total_wait_seconds/10)); i++)); do
            sleep 10
            check_gcm_trigger
        done
        # 处理剩余的秒数
        remaining_seconds=$((total_wait_seconds % 10))
        if [ $remaining_seconds -gt 0 ]; then
            sleep $remaining_seconds
            check_gcm_trigger
        fi
    else
        echo "已经在整点，立即开始。"
    fi
}

# 等待下一个小时（带中断检查）
wait_until_next_hour() {
    echo "等待3600秒直到下一个整点..."
    # 分段睡眠，定期检查中断信号
    for ((i=0; i<360; i++)); do
        sleep 10
        check_gcm_trigger
        
        # 每300秒（5分钟）校准一次时间
        if [ $((i % 30)) -eq 0 ] && [ $i -ne 0 ]; then
            echo "$(date): 每5分钟进行一次时间校准检查..."
            # 获取当前秒数
            current_second=$(date +%S)
            # 如果秒数不是在0-5秒范围内，则进行微调
            if [ $current_second -gt 5 ]; then
                wait_seconds=$((60 - current_second))
                echo "$(date): 检测到时间偏差，等待 $wait_seconds 秒进行校准..."
                sleep $wait_seconds
            fi
        fi
    done
}

# 每5分钟校准一次时间（新增函数）
calibrate_timer() {
    echo "$(date): 开始时间校准..."
    
    # 获取当前时间
    current_minute=$(date +%M)
    current_second=$(date +%S)
    
    # 计算到下一个5分钟整数倍的时间点还需要多少秒
    minutes_to_next_5min=$((5 - (current_minute % 5)))
    if [ $minutes_to_next_5min -eq 5 ]; then
        minutes_to_next_5min=0
    fi
    
    # 如果秒数大于0，则需要额外等待到下一分钟
    if [ $current_second -gt 0 ]; then
        seconds_to_wait=$((60 - current_second))
    else
        seconds_to_wait=0
    fi
    
    # 总共需要等待的秒数
    total_wait_seconds=$((minutes_to_next_5min * 60 + seconds_to_wait))
    
    # 如果需要等待，则进行等待
    if [ $total_wait_seconds -gt 0 ]; then
        echo "$(date): 等待 $total_wait_seconds 秒以校准到5分钟整数倍时间点..."
        sleep $total_wait_seconds
    fi
    
    echo "$(date): 定时器校准完成"
}

# 检查并打开网站
check_and_open_website() {
    echo "检查时间并执行任务..."
    
    # 获取当前小时
    current_hour=$(date +%H)
    
    # 只在工作时间执行 (9点到17点)打开网站
    if [ $current_hour -ge 9 ] && [ $current_hour -le 17 ]; then
        echo "在工作时间 $(date) 打开网站..."
        open_random_website
    else
        echo "在工作时间之外 ($(date))，跳过网站打开..."
    fi
    
    # 执行repo_commit.sh脚本，全天24小时执行
    echo "执行repo_commit.sh脚本..."
    execute_repo_commit
}

# 执行repo_commit.sh脚本
execute_repo_commit() {
    # 查找并执行repo_commit.sh脚本
    script_paths=(
        "../../matrix_shell/scripts/plugins/repo_commit.sh"
        "../../agent/scripts/plugins/repo_commit.sh"
        "$(dirname "$0")/repo_commit.sh"
    )
    
    for script_path in "${script_paths[@]}"; do
        if [ -f "$script_path" ]; then
            echo "运行repo_commit.sh..."
            bash "$script_path"
            return
        fi
    done
    
    echo "警告: 未找到repo_commit.sh脚本。"
}

# 打开随机网站
open_random_website() {
    # 生成随机数并选择URL (0-278，共279个网站)
    rand=$((RANDOM % 279))
    
    # 网站列表（280个国内知名网站）
    declare -a websites=(
        # 搜索引擎 (0-9)
        "https://www.baidu.com"
        "https://www.sogou.com"
        "https://cn.bing.com"
        "https://www.360.cn"
        "https://www.hao123.com"
        "https://www.google.com.hk"
        "https://www.duckduckgo.com"
        "https://www.yandex.com"
        "https://www.ecosia.org"
        "https://www.startpage.com"
        
        # 社交平台 (10-29)
        "https://www.weibo.com"
        "https://www.zhihu.com"
        "https://www.douban.com"
        "https://www.v2ex.com"
        "https://www.xiaohongshu.com"
        "https://www.tianya.cn"
        "https://www.jianshu.com"
        "https://www.lofter.com"
        "https://www.mafengwo.cn"
        "https://www.douban.com/group"
        "https://www.kaixin001.com"
        "https://www.renren.com"
        "https://www.pengyou.com"
        "https://qzone.qq.com"
        "https://tieba.baidu.com"
        "https://www.tumblr.com"
        "https://www.instagram.com"
        "https://www.twitter.com"
        "https://www.facebook.com"
        "https://www.linkedin.com"
        
        # 电商平台 (30-69)
        "https://www.taobao.com"
        "https://www.tmall.com"
        "https://www.jd.com"
        "https://www.pinduoduo.com"
        "https://www.suning.com"
        "https://www.vip.com"
        "https://www.gome.com.cn"
        "https://www.amazon.cn"
        "https://www.aliyun.com"
        "https://www.alibaba.com"
        "https://www.yhd.com"
        "https://www.mogujie.com"
        "https://www.58.com"
        "https://www.ganji.com"
        "https://www.baixing.com"
        "https://www.anjuke.com"
        "https://www.lianjia.com"
        "https://fang.com"
        "https://www.ke.com"
        "https://www.5i5j.com"
        "https://www.dianping.com"
        "https://www.nuomi.com"
        "https://www.meituan.com"
        "https://www.ele.me"
        "https://www.mi.com"
        "https://www.huawei.com"
        "https://www.apple.com.cn"
        "https://www.samsung.com"
        "https://www.oppo.com"
        "https://www.vivo.com"
        "https://shop.m.jd.com"
        "https://www.yixun.com"
        "https://www.dangdang.com"
        "https://www.amazon.com"
        "https://www.ebay.com"
        "https://www.wish.com"
        "https://www.aliexpress.com"
        "https://www.lightinthebox.com"
        "https://www.dx.com"
        "https://www.gearbest.com"
        "https://www.banggood.com"
        
        # 视频平台 (70-99)
        "https://www.bilibili.com"
        "https://www.iqiyi.com"
        "https://www.youku.com"
        "https://www.mgtv.com"
        "https://www.douyin.com"
        "https://www.acfun.cn"
        "https://www.1905.com"
        "https://www.xigua.com"
        "https://v.qq.com"
        "https://tv.cctv.com"
        "https://www.kankan.com"
        "https://www.pptv.com"
        "https://www.le.com"
        "https://www.fun.tv"
        "https://www.yinyuetai.com"
        "https://www.kugou.com"
        "https://www.kuwo.cn"
        "https://music.baidu.com"
        "https://y.qq.com"
        "https://music.163.com"
        "https://www.xiami.com"
        "https://www.luoo.net"
        "https://www.douban.com/music"
        "https://www.5sing.com"
        "https://www.huya.com"
        "https://www.douyu.com"
        "https://www.panda.tv"
        "https://www.zhanqi.tv"
        "https://www.longzhu.com"
        "https://www.quanmin.tv"
        
        # 新闻资讯 (100-139)
        "https://www.163.com"
        "https://www.sina.com.cn"
        "https://www.sohu.com"
        "https://www.qq.com"
        "https://www.ifeng.com"
        "https://www.xinhuanet.com"
        "https://www.people.com.cn"
        "https://www.toutiao.com"
        "https://www.36kr.com"
        "https://www.ifanr.com"
        "https://www.pingwest.com"
        "https://www.geekpark.net"
        "https://www.ithome.com"
        "https://www.cnbeta.com"
        "https://www.leiphone.com"
        "https://www.techweb.com.cn"
        "https://www.donews.com"
        "https://www.huxiu.com"
        "https://www.iyiou.com"
        "https://www.tmtpost.com"
        "https://www.woshipm.com"
        "https://www.yixieshi.com"
        "https://www.chanpin100.com"
        "https://www.pmtoo.com"
        "https://www.jiemian.com"
        "https://www.thepaper.cn"
        "https://www.guancha.cn"
        "https://www.voachinese.com"
        "https://www.bbc.com/zhongwen/simp"
        "https://www.dw.com/zh"
        "https://www.rfi.fr/cn"
        "https://www.zaobao.com"
        "https://www.stnn.cc"
        "https://www.backchina.com"
        "https://www.wenxuecity.com"
        "https://www.6park.com"
        "https://www.mitbbs.com"
        "https://www.huaren.us"
        
        # 教育学习 (140-169)
        "https://www.fenbi.com"
        "https://www.nowcoder.com"
        "https://www.zuoyebang.com"
        "https://www.zhihuishu.com"
        "https://ke.qq.com"
        "https://www.xuetangx.com"
        "https://www.100.com"
        "https://www.coursera.org"
        "https://www.imooc.com"
        "https://www.liaoxuefeng.com"
        "https://www.jianshu.com"
        "https://www.cnblogs.com"
        "https://www.csdn.net"
        "https://www.oschina.net"
        "https://www.segmentfault.com"
        "https://www.v2ex.com"
        "https://www.zhihu.com"
        "https://www.douban.com/group/explore"
        "https://www.guokr.com"
        "https://www.sciencenet.cn"
        "https://www.mathchina.com"
        "https://www.chinaventure.com.cn"
        "https://www.eeo.com.cn"
        "https://www.economist.com"
        "https://www.nature.com"
        "https://www.sciencemag.org"
        "https://www.cell.com"
        "https://www.pnas.org"
        "https://www.pLoS.org"
        "https://www.biomedcentral.com"
        
        # 技术社区 (170-189)
        "https://www.csdn.net"
        "https://www.cnblogs.com"
        "https://www.oschina.net"
        "https://www.jianshu.com"
        "https://www.segmentfault.com"
        "https://gitee.com"
        "https://github.com"
        "https://gitlab.com"
        "https://stackoverflow.com"
        "https://www.reddit.com"
        "https://news.ycombinator.com"
        "https://dribbble.com"
        "https://www.behance.net"
        "https://codepen.io"
        "https://jsfiddle.net"
        "https://stackoverflow.com/questions"
        "https://github.com/explore"
        "https://www.v2ex.com/?tab=tech"
        "https://www.zhihu.com/topic/19552832"
        "https://www.douban.com/group/tech"
        
        # 汽车网站 (190-199)
        "https://www.autohome.com.cn"
        "https://www.bitauto.com"
        "https://www.cheshi.com"
        "https://www.pcauto.com.cn"
        "https://www.xcar.com.cn"
        "https://www.autohome.com.cn/news"
        "https://www.58che.com"
        "https://www.autoworld.com.cn"
        "https://www.qc188.com"
        "https://www.cnautonews.com"
        
        # 科技公司官网 (200-219)
        "https://www.tencent.com"
        "https://www.bytedance.com"
        "https://www.xiaomi.com"
        "https://www.huawei.com"
        "https://www.oppo.com"
        "https://www.vivo.com"
        "https://www.apple.com.cn"
        "https://www.samsung.com"
        "https://www.sony.com.cn"
        "https://www.lenovo.com.cn"
        "https://www.dell.com.cn"
        "https://www.hp.com.cn"
        "https://www.asus.com.cn"
        "https://www.acer.com.cn"
        "https://www.msi.com"
        "https://www.razerzone.com"
        "https://www.logitech.com.cn"
        "https://www.seagate.com.cn"
        "https://www.wd.com.cn"
        "https://www.intel.cn"
        
        # 工具服务 (220-239)
        "https://www.smzdm.com"
        "https://www.xunlei.com"
        "https://www.huaban.com"
        "https://www.bangumi.tv"
        "https://www.douban.com/location"
        "https://www.last.fm"
        "https://www.goodreads.com"
        "https://www.quora.com"
        "https://www.stackexchange.com"
        "https://www.reddit.com/r/programming"
        "https://www.metafilter.com"
        "https://www.boingboing.net"
        "https://www.lifehacker.com"
        "https://www.makeuseof.com"
        "https://www.howtogeek.com"
        "https://www.tutorialspoint.com"
        "https://www.w3schools.com"
        "https://www.geeksforgeeks.org"
        "https://www.leetcode.com"
        "https://www.hackerrank.com"
        
        # 金融理财 (240-259)
        "https://www.eastmoney.com"
        "https://www.10jqka.com.cn"
        "https://www.cnfol.com"
        "https://www.jrj.com.cn"
        "https://www.sina.com.cn/finance"
        "https://finance.sina.com.cn"
        "https://finance.qq.com"
        "https://www.hexun.com"
        "https://www.ftchinese.com"
        "https://www.wsj.com"
        "https://www.bloomberg.com"
        "https://www.reuters.com"
        "https://www.cnbc.com"
        "https://www.marketwatch.com"
        "https://www.investopedia.com"
        "https://www.money.cnn.com"
        "https://www.forbes.com"
        "https://www.fortune.com"
        "https://www.businessinsider.com"
        "https://www.entrepreneur.com"
        
        # 生活娱乐 (260-279)
        "https://www.dianping.com"
        "https://www.meituan.com"
        "https://www.nuomi.com"
        "https://www.lashou.com"
        "https://www.fantong.com"
        "https://www.55tuan.com"
        "https://www.aibang.com"
        "https://www.ganji.com"
        "https://www.baixing.com"
        "https://www.58.com"
        "https://www.ganji.com"
        "https://www.baixing.com"
        "https://www.anjuke.com"
        "https://www.lianjia.com"
        "https://www.ke.com"
        "https://www.5i5j.com"
        "https://www.mayi.com"
        "https://www.ziroom.com"
        "https://www.danke.com"
        "https://www.qk365.com"
    )
    
    if [ $rand -lt ${#websites[@]} ]; then
        selected_url="${websites[$rand]}"
        echo "打开网站: $selected_url"
        
        # 根据系统类型使用不同的命令打开浏览器
        if [[ "$OSTYPE" == "darwin"* ]]; then
            # macOS
            open "$selected_url"
        elif [[ "$OSTYPE" == "linux-gnu"* ]]; then
            # Linux
            if command -v xdg-open > /dev/null; then
                xdg-open "$selected_url"
            elif command -v gnome-open > /dev/null; then
                gnome-open "$selected_url"
            else
                echo "无法打开浏览器，请手动访问: $selected_url"
            fi
        else
            echo "不支持的操作系统，请手动访问: $selected_url"
        fi
    else
        echo "随机数超出网站列表范围: $rand"
    fi
}

# 主循环
main() {
    echo "启动后台任务脚本..."
    
    # 等待到下一个整点
    wait_until_full_hour
    
    # 初始化计数器
    calibration_counter=0
    
    # 主循环
    while true; do
        check_and_open_website
        
        # 每12次循环（约12小时）进行一次时间校准
        calibration_counter=$((calibration_counter + 1))
        if [ $calibration_counter -ge 12 ]; then
            calibrate_timer
            calibration_counter=0
        fi
        
        wait_until_next_hour
    done
}

# 如果脚本被直接执行，运行主函数
if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then
    main "$@"
fi